/**
 * 
 */
package com.itmayiedu.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.itmayiedu.annotation.ResponseResult;
import com.itmayiedu.entity.User;
import com.itmayiedu.exception.UserNotExistException;
import com.itmayiedu.exception.ValidatatorException;
import com.itmayiedu.jpa.UserJPA;
import com.itmayiedu.utils.ConstantUtil;


/**
 * @author Administrator
 * @date 2019年5月2日
 */

@RestController
@RequestMapping("/user")//在类上声明了/user，在方法中就可以省略了
public class UserController extends BaseController {
	Logger logger = LoggerFactory.getLogger("mytest");
	Logger loggerUserController = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	public UserJPA userJPA;
	
	//使用的时候加上@Valid注解开启valid校验。
	@PostMapping
	public User create(@Valid @RequestBody User user,BindingResult errors) {
		
		if(errors.hasErrors()) {
			//有错误返回true
			String defaultMessage = errors.getAllErrors().iterator().next().getDefaultMessage();
			throw new ValidatatorException(-2, defaultMessage);
		}
		userJPA.save(user);
		return user;
	}
	
	//使用的时候加上@Valid注解开启valid校验。
	@PostMapping("{id:\\d+}")
	public User update(@PathVariable String id, @Valid @RequestBody User user,BindingResult errors) {
		
		if(errors.hasErrors()) {
			//有错误返回true
			String defaultMessage = errors.getAllErrors().iterator().next().getDefaultMessage();
			throw new ValidatatorException(-2, defaultMessage);
		}
		user.setName(user.getName()+" updated");
		loggerUserController.info(user.toString() + ", id: " + id);
		return user;
	}

	@DeleteMapping("{id:\\d+}")
	public void delete(@PathVariable Integer id) {
		
		userJPA.deleteById(id);
		System.out.println("用户删除，ID为： " + id);
		
		return;
	}
	
	@GetMapping("{id:\\d+}")
	@JsonView(User.UserDetailView.class)
	//@PathVariable 解析形如： /user/lilei 的url
	public User getUser(@PathVariable String id, ModelMap modelMap,HttpServletRequest request){
		Optional<User> user = null;
		if(Integer.valueOf(id) != 1){
//			user = new User(Integer.valueOf(id),"xiaoming","123456","");	
			user = userJPA.findById(Integer.parseInt(id));
		}else {
			throw new UserNotExistException(-1, "user not found, id:"+ Integer.valueOf(id));
		}
		logger.info(user.toString() + "  modelMap:" + modelMap.get("author"));
		loggerUserController.info(user.toString() + "  modelMap:" + modelMap.get("author"));
		
		//Long.ValueOf("String")返回Long包装类型
		//Long.parseLong("String")返回long基本数据类型
		
		request.setAttribute(ConstantUtil.LOGGER_RETURN	, user);
		return user.get();
	}

	@GetMapping("/query")
	@JsonView(User.UserSimpleView.class) //这个查询就会缺少password字段
	//@RequestParam 解析形如： /user/query?name=lilei 的url
	//public List<User> getUserList(@RequestParam(name="name",required=false,defaultValue="tom") String userName){
	public List<User> getUserList(String userName){
		System.out.println("/query?name=" + userName);
		ArrayList<User> arrayList = new ArrayList<User>();
		if(!StringUtils.isEmpty(userName) && userName.equals("jim")){
			User user1 = new User(1,"jim","123456","");
			arrayList.add(user1);
		}else {
//			User user1 = new User(1,"xiaoming","123456","");
//			User user2 = new User(2,"xiaohong","123456","");
//			arrayList.add(user1);
//			arrayList.add(user2);
			return userJPA.findAll();
		}
		
		logger.info(arrayList.toString());
		return arrayList;
	}

}
